//
//  SettingAlarmViewController.m
//  JiuLe
//
//  Created by xcq on 15/11/10.
//  Copyright © 2015年 Fine. All rights reserved.
//
#import "JLClockModel.h"
#import "SocketManager.h"
#import "AlarmTableViewCell.h"
#import "SetAlarmViewController.h"
#import "SettingAlarmViewController.h"
#define kCellHeight 47
static NSString *cellIdentifier = @"alarm";

@interface SettingAlarmViewController () <UITableViewDataSource,UITableViewDelegate>{
    NSMutableArray *alarms;
    NSMutableArray *typeArr;
}
@property (weak, nonatomic) IBOutlet UIButton *saveBtn;
@end

@implementation SettingAlarmViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.title = @"设置闹钟";
    _isChange = NO;
    [self showNavBarWithRightTitle:nil
                    andRightAction:nil
                     andLeftAction:@selector(homeControllerBackTo)
                 andRightBtnIsShow:NO];
    [self setUpTable];
    [self netRequest];
}

- (void)viewWillAppear:(BOOL)animated {
    if (alarms.count > 0 && _isChange == YES) {
        [SVProgressHUD dismiss];
        [alarms removeAllObjects];
        JLClockModel *dic1 = [NSUserDefaults objectUserForKey:UserDataAlarmArraysOne];
        JLClockModel *dic2 = [NSUserDefaults objectUserForKey:UserDataAlarmArraysTwo];
        JLClockModel *dic3 = [NSUserDefaults objectUserForKey:UserDataAlarmArraysThree];
        [alarms addObject:dic1];
        [alarms addObject:dic2];
        [alarms addObject:dic3];
        [self.tableView reloadData];
        _isChange = NO;
    }
}

- (void)setAlarm {
    if (alarms.count == 0) {
        JLClockModel *alarm = [NSUserDefaults objectUserForKey:UserDataAlarmArraysOne];
        if (alarm == nil) {
            NSDictionary *dic = @{@"remind_type" : @(1), @"clock" : @"0000", @"is_set":@(0),@"type":@(1)};
            NSDictionary *dic1 = @{@"remind_type" : @(1), @"clock" : @"0000", @"is_set":@(0),@"type":@(2)};
            NSDictionary *dic2 = @{@"remind_type" : @(1), @"clock" : @"0000", @"is_set":@(0),@"type":@(3)};
            JLClockModel *model = [JLClockModel objectWithKeyValues:dic];
            JLClockModel *model1 = [JLClockModel objectWithKeyValues:dic1];
            JLClockModel *model2 = [JLClockModel objectWithKeyValues:dic2];
            
            [NSUserDefaults setUserObject:model forKey:UserDataAlarmArraysOne];
            [NSUserDefaults setUserObject:model1 forKey:UserDataAlarmArraysTwo];
            [NSUserDefaults setUserObject:model2 forKey:UserDataAlarmArraysThree];
            
            [alarms addObject:model];
            [alarms addObject:model1];
            [alarms addObject:model2];
        } else {
            JLClockModel *dic1 = [NSUserDefaults objectUserForKey:UserDataAlarmArraysOne];
            JLClockModel *dic2 = [NSUserDefaults objectUserForKey:UserDataAlarmArraysTwo];
            JLClockModel *dic3 = [NSUserDefaults objectUserForKey:UserDataAlarmArraysThree];
            [alarms addObject:dic1];
            [alarms addObject:dic2];
            [alarms addObject:dic3];
        }
    } else if (alarms.count < 3) {
        NSInteger count = typeArr.count;
        if (count == 1) {
            NSInteger type = [[typeArr firstObject] integerValue];
            if (type == 1) {
                NSDictionary *dic1 = @{@"remind_type" : @(1), @"clock" : @"0000", @"is_set":@(0),@"type":@(2)};
                NSDictionary *dic2 = @{@"remind_type" : @(1), @"clock" : @"0000", @"is_set":@(0),@"type":@(3)};
                JLClockModel *model = [JLClockModel objectWithKeyValues:dic1];
                JLClockModel *model2 = [JLClockModel objectWithKeyValues:dic2];
                [NSUserDefaults setUserObject:alarms[0] forKey:UserDataAlarmArraysOne];
                [NSUserDefaults setUserObject:model forKey:UserDataAlarmArraysTwo];
                [NSUserDefaults setUserObject:model2 forKey:UserDataAlarmArraysThree];
                [alarms addObject:model];
                [alarms addObject:model2];
            } else if (type == 2){
                NSDictionary *dic1 = @{@"remind_type" : @(1), @"clock" : @"0000", @"is_set":@(0),@"type":@(1)};
                NSDictionary *dic2 = @{@"remind_type" : @(1), @"clock" : @"0000", @"is_set":@(0),@"type":@(3)};
                JLClockModel *model = [JLClockModel objectWithKeyValues:dic1];
                JLClockModel *model2 = [JLClockModel objectWithKeyValues:dic2];
                [NSUserDefaults setUserObject:model forKey:UserDataAlarmArraysOne];
                [NSUserDefaults setUserObject:alarms[0] forKey:UserDataAlarmArraysTwo];
                [NSUserDefaults setUserObject:model2 forKey:UserDataAlarmArraysThree];
                [alarms addObject:model];
                [alarms addObject:model2];
            } else {
                NSDictionary *dic1 = @{@"remind_type" : @(1), @"clock" : @"0000", @"is_set":@(0),@"type":@(1)};
                NSDictionary *dic2 = @{@"remind_type" : @(1), @"clock" : @"0000", @"is_set":@(0),@"type":@(2)};
                
                JLClockModel *model = [JLClockModel objectWithKeyValues:dic1];
                JLClockModel *model2 = [JLClockModel objectWithKeyValues:dic2];
                
                [NSUserDefaults setUserObject:model forKey:UserDataAlarmArraysOne];
                [NSUserDefaults setUserObject:model2 forKey:UserDataAlarmArraysTwo];
                [NSUserDefaults setUserObject:alarms[0] forKey:UserDataAlarmArraysThree];

                
                [alarms addObject:model];
                [alarms addObject:model2];
            }
        } else if (count == 2){
            NSInteger type = [[typeArr firstObject] integerValue];
            NSInteger type1 = [[typeArr lastObject] integerValue];
            
            if ((type == 1 && type1 == 2) || (type == 2 && type1 == 1)) {
                NSDictionary *dic2 = @{@"remind_type" : @(1), @"clock" : @"0000", @"is_set":@(0),@"type":@(3)};
                JLClockModel *model2 = [JLClockModel objectWithKeyValues:dic2];
                [NSUserDefaults setObject:model2 forKey:UserDataAlarmArraysThree];
                if (type == 1) {
                    [NSUserDefaults setUserObject:[alarms firstObject] forKey:UserDataAlarmArraysOne];
                    [NSUserDefaults setUserObject:[alarms lastObject] forKey:UserDataAlarmArraysTwo];
                } else {
                    [NSUserDefaults setUserObject:[alarms firstObject] forKey:UserDataAlarmArraysTwo];
                    [NSUserDefaults setUserObject:[alarms lastObject] forKey:UserDataAlarmArraysOne];
                }
               
            } else if ((type == 1 && type1 == 3) || (type == 3 && type1 == 1)) {
                NSDictionary *dic2 = @{@"remind_type" : @(1), @"clock" : @"0000", @"is_set":@(0),@"type":@(2)};
                JLClockModel *model2 = [JLClockModel objectWithKeyValues:dic2];
                [NSUserDefaults setObject:model2 forKey:UserDataAlarmArraysTwo];
                if (type == 1) {
                    [NSUserDefaults setUserObject:[alarms firstObject] forKey:UserDataAlarmArraysOne];
                    [NSUserDefaults setUserObject:[alarms lastObject] forKey:UserDataAlarmArraysThree];
                } else {
                    [NSUserDefaults setUserObject:[alarms firstObject] forKey:UserDataAlarmArraysThree];
                    [NSUserDefaults setUserObject:[alarms lastObject] forKey:UserDataAlarmArraysOne];
                }
            
            } else if ((type == 2 && type1 == 3) || (type == 3 && type1 == 2)) {
                NSDictionary *dic2 = @{@"remind_type" : @(1), @"clock" : @"0000", @"is_set":@(0),@"type":@(1)};
                JLClockModel *model2 = [JLClockModel objectWithKeyValues:dic2];
                [NSUserDefaults setObject:model2 forKey:UserDataAlarmArraysOne];
                if (type == 2) {
                    [NSUserDefaults setUserObject:[alarms firstObject] forKey:UserDataAlarmArraysTwo];
                    [NSUserDefaults setUserObject:[alarms lastObject] forKey:UserDataAlarmArraysThree];
                } else {
                    [NSUserDefaults setUserObject:[alarms firstObject] forKey:UserDataAlarmArraysThree];
                    [NSUserDefaults setUserObject:[alarms lastObject] forKey:UserDataAlarmArraysOne];
                }
            }
        }
    } else if (alarms.count > 3) {
        NSMutableArray *currenArr = [NSMutableArray new];
        NSMutableArray *arr = [NSMutableArray arrayWithArray:@[@"1",@"2",@"3"]];
        for (int i = 0 ; i < alarms.count; i ++) {
            JLClockModel *model = alarms[i];
            if (arr.count > 0 && [arr containsObject:model.type]) {
                [currenArr addObject:model];
                [arr removeObject:model.type];
                if ([model.type isEqualToString:@"1"]) {
                    [NSUserDefaults setUserObject:model forKey:UserDataAlarmArraysOne];
                } else if ([model.type isEqualToString:@"2"]) {
                    [NSUserDefaults setUserObject:model forKey:UserDataAlarmArraysTwo];
                } else {
                    [NSUserDefaults setUserObject:model forKey:UserDataAlarmArraysThree];
                }
            }
        }
        [alarms removeAllObjects];
        alarms = [currenArr mutableCopy];
    } else if (alarms.count == 3) {
        for (int i = 0; i < alarms.count ; i ++) {
            JLClockModel *model = alarms[i];
            if ([model.type integerValue] == 1) {
                [NSUserDefaults setUserObject:model forKey:UserDataAlarmArraysOne];
            } else if ([model.type integerValue] == 2) {
                [NSUserDefaults setUserObject:model forKey:UserDataAlarmArraysTwo];
            } else if ([model.type integerValue] == 3) {
                [NSUserDefaults setUserObject:model forKey:UserDataAlarmArraysThree];
            }
        }
    }
  
    if (_tableView.delegate == nil) {
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    [SVProgressHUD dismiss];
    [_tableView reloadData];
}

- (IBAction)saveAction:(id)sender {
    if (![SocketManager sharedInstance].socket.isConnected) {
        [SVProgressHUD showErrorWithStatus:@"当前未连接到久乐表，无法保存数据"];
        return;
    }
    NSMutableArray *arr = [NSMutableArray new];
    
    JLClockModel *dic1 = [NSUserDefaults objectUserForKey:UserDataAlarmArraysOne];
    JLClockModel *dic2 = [NSUserDefaults objectUserForKey:UserDataAlarmArraysTwo];
    JLClockModel *dic3 = [NSUserDefaults objectUserForKey:UserDataAlarmArraysThree];
    
    NSArray *arrTemp = @[dic1,dic2,dic3];
    for (int i = 0; i < arrTemp.count; i ++) {
        JLClockModel *dic = arrTemp[i];
        if (dic!=nil && dic.clock!=nil) {
            [arr addObject:[[[dic.clock substringWithRange:NSMakeRange(0, 2)] stringByAppendingString:@":"] stringByAppendingString:[dic.clock substringWithRange:NSMakeRange(2, 2)]]];
        }
    }
    [[SocketManager sharedInstance] writeAlarmClock:arr];
    TIPS(@"设置成功");
}

- (void)netRequest {
    [SVProgressHUD showWithStatus:@"加载中..."];
    if (alarms == nil) {
        alarms = [NSMutableArray new];
        typeArr = [NSMutableArray new];
    }
//    NSString *netStatus = [[NSUserDefaults standardUserDefaults] objectForKey:JiuLeNetBility];
    if ([SocketManager sharedInstance].socket.isConnected || [[NSUserDefaults standardUserDefaults] boolForKey:JiuLeOfflineMode] ) {
        [self setAlarm];
    } else {        
        [InterfaceNetManager RequestClockSettingCompletion:^(BOOL isSucceed,
                                                          NSString *message,
                                                                    id data,
                                                             NSError *error) {
            NSArray *dataArr;
            if (data == nil || data == [NSNull null]) {
                dataArr = [NSArray array];
            } else {
                dataArr  = (NSArray *)data;
            }
            for (int i = 0; i < dataArr.count; i ++) {
                JLClockModel *model = [JLClockModel objectWithKeyValues:[dataArr objectAtIndex:i]];
                if ([model.clock isEqualToString:@""] || model.clock == nil) {
                    model.clock = @"0000";
                }
                [alarms addObject:model];
                [typeArr addObject:model.type];
            }
            [self setAlarm];
            [SVProgressHUD dismiss];
        }];
    }
}

- (void)setUpTable {
    [_tableView registerNib:[UINib nibWithNibName:@"AlarmTableViewCell" bundle:nil]
     forCellReuseIdentifier:cellIdentifier];
    _tableView.tableFooterView = [UIView new];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AlarmTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    cell.model = alarms[indexPath.row];
    cell.tag = indexPath.row;
    cell.callBack = ^(int index , JLClockModel *model , int tag) {
        if (index == 0) {
            SetAlarmViewController *alarm = [[SetAlarmViewController alloc] initWithNibName:@"SetAlarmViewController" bundle:nil];
            alarm.index = (int)indexPath.row;
            alarm.model = model;
            alarm.weakAlarm = self;
            [self.navigationController pushViewController:alarm animated:YES];
        } else {
            [alarms replaceObjectAtIndex:tag withObject:model];
        }
    };
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return alarms.count > 0 ? alarms.count : 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 47;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
